package com.example.demo.util;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiNetworkSpecifier;
import android.os.Build;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import java.util.List;

public class WifiUtils {
    private static final String TAG = "WifiUtils";

    private Context context;
    private WifiManager wifiManager;
    private WifiScanReceiver wifiScanReceiver;
    private WifiConnectionReceiver wifiConnectionReceiver;
    private OnWifiScanListener onWifiScanListener;
    private OnWifiConnectionListener onWifiConnectionListener;

    private static volatile WifiUtils instance;

    private WifiUtils(Context context) {
        this.context = context.getApplicationContext();
        wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    }

    /**
     * 初始化 Wi-Fi 工具类
     * @param context
     * @return
     */
    public static WifiUtils getInstance(@NonNull Context context) {
        if (instance == null) {
            synchronized (WifiUtils.class) {
                if (instance == null) {
                    instance = new WifiUtils(context);
                }
            }
        }
        return instance;
    }

    /**
     * 检查 Wi-Fi 是否启用
     * @return
     */
    public boolean isWifiEnabled() {
        return wifiManager != null && wifiManager.isWifiEnabled();
    }

    /**
     * 打开 Wi-Fi
     */
    public void openWifi() {
        if (wifiManager != null && !wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
    }

    /**
     * 关闭 Wi-Fi
     */
    public void closeWifi() {
        if (wifiManager != null && wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(false);
        }
    }

    /**
     * 启动扫描 Wi-Fi
     */
    public void startScan() {
        if (wifiManager != null && wifiManager.isWifiEnabled()) {
            if (wifiScanReceiver == null) {
                wifiScanReceiver = new WifiScanReceiver();
            }
            registerWifiScanReceiver();
            wifiManager.startScan();
        }
    }


    /**
     * 连接到 Wi-Fi 网络
     * @param ssid    Wi-Fi名称
     * @param preSharedKey  Wi-Fi密码
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.Q)
    public boolean connectToWifi(String ssid, String preSharedKey) {
        WifiNetworkSpecifier.Builder builder = new WifiNetworkSpecifier.Builder();
        builder.setSsid(ssid);

        if (preSharedKey != null) {
            builder.setWpa2Passphrase(preSharedKey);
        }

        WifiNetworkSpecifier wifiNetworkSpecifier = builder.build();

        NetworkRequest.Builder requestBuilder = new NetworkRequest.Builder();
        requestBuilder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
        requestBuilder.setNetworkSpecifier(wifiNetworkSpecifier);

        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
                @Override
                public void onAvailable(Network network) {
                    super.onAvailable(network);
                    // 连接成功回调处理
                    // ...
                }

                @Override
                public void onUnavailable() {
                    super.onUnavailable();
                    // 连接失败回调处理
                    // ...
                }
            };

            connectivityManager.requestNetwork(requestBuilder.build(), networkCallback);

            return true;
        }

        return false;
    }


    /**
     * 获取当前连接的 Wi-Fi 详细信息
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Nullable
    public WifiInfo getConnectedWifiInfo() {
        if (wifiManager != null && wifiManager.isWifiEnabled()) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivityManager != null) {
                Network network = connectivityManager.getActiveNetwork();
                NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(network);
                if (networkCapabilities != null && networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                    return wifiManager.getConnectionInfo();
                }
            }
        }
        return null;
    }

    /**
     * 获取当前连接的 Wi-Fi 名称
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Nullable
    public String getConnectedWifiName() {
        WifiInfo wifiInfo = getConnectedWifiInfo();
        if (wifiInfo != null) {
            return wifiInfo.getSSID().replace("\"", "");
        }
        return null;
    }

    /**
     * 获取当前 IP 地址
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Nullable
    public String getIpAddress() {
        WifiInfo wifiInfo = getConnectedWifiInfo();
        if (wifiInfo != null) {
            int ipAddress = wifiInfo.getIpAddress();
            return ((ipAddress >> 0) & 0xFF) + "." +
                    ((ipAddress >> 8) & 0xFF) + "." +
                    ((ipAddress >> 16) & 0xFF) + "." +
                    ((ipAddress >> 24) & 0xFF);
        }
        return null;
    }

    /**
     * 获取 Wi-Fi 列表
     * @return
     */
    @SuppressLint("MissingPermission")
    public List<ScanResult> getWifiList() {
        return wifiManager.getScanResults();
    }

    /**
     * 注册 Wi-Fi 连接状态广播接收器
     * @param listener
     */
    public void registerWifiConnectionReceiver(@NonNull OnWifiConnectionListener listener) {
        this.onWifiConnectionListener = listener;
        if (wifiConnectionReceiver == null) {
            wifiConnectionReceiver = new WifiConnectionReceiver();
        }
        registerWifiConnectionReceiver();
    }

    /**
     * 解除注册 Wi-Fi 连接状态广播接收器
     */
    public void unregisterWifiConnectionReceiver() {
        if (wifiConnectionReceiver != null) {
            context.unregisterReceiver(wifiConnectionReceiver);
            wifiConnectionReceiver = null;
        }
        onWifiConnectionListener = null;
    }

    private void registerWifiScanReceiver() {
        IntentFilter intentFilter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        context.registerReceiver(wifiScanReceiver, intentFilter);
    }

    private void unregisterWifiScanReceiver() {
        if (wifiScanReceiver != null) {
            context.unregisterReceiver(wifiScanReceiver);
            wifiScanReceiver = null;
        }
        onWifiScanListener = null;
    }

    private void registerWifiConnectionReceiver() {
        IntentFilter intentFilter = new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        context.registerReceiver(wifiConnectionReceiver, intentFilter);
    }

    private class WifiScanReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            @SuppressLint("MissingPermission") List<ScanResult> scanResults = wifiManager.getScanResults();
            if (onWifiScanListener != null) {
                onWifiScanListener.onWifiScanResults(scanResults);
            }
            context.unregisterReceiver(this);
            wifiScanReceiver = null;
        }
    }

    private class WifiConnectionReceiver extends BroadcastReceiver {
        @SuppressLint("MissingPermission")
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
                ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                if (connectivityManager != null) {
                    Network network = connectivityManager.getActiveNetwork();
                    NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(network);
                    if (networkCapabilities != null && networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                        if (wifiInfo != null && wifiInfo.getNetworkId() != -1) {
                            if (onWifiConnectionListener != null) {
                                onWifiConnectionListener.onWifiConnected();
                            }
                        } else {
                            if (onWifiConnectionListener != null) {
                                onWifiConnectionListener.onWifiDisconnected();
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 释放 Wi-Fi 工具类实例
     */
    public void release() {
        context = null;
        unregisterWifiScanReceiver();
        unregisterWifiConnectionReceiver();
        instance = null;
    }

    public interface OnWifiScanListener {
        void onWifiScanResults(List<ScanResult> scanResults);
    }

    public interface OnWifiConnectionListener {
        void onWifiConnected();

        void onWifiDisconnected();
    }
}